/**
 * 设置分拣道口
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import { Form, message, InputNumber } from 'antd';
import { setOutNum } from '../../service';

const AddSortCross = ({ record, handleOk, handleCancel }) => {
  const [form] = Form.useForm();

  const [open, setOpen] = useState(false);

  const [isOk, setIsOk] = useState(false);

  const onOk = () => {
    form.validateFields().then((val) => {
      handleSubmit(val);
    });
  };

  useEffect(() => {
    setOpen(true)
  }, []);

  const handleSubmit = async (val) => {
    START_LOADING();
    const { success, msg } = await setOutNum({
      ...val,
      networkId: record.networkId,
    });
    if (success) {
      message.success(msg);
      setOpen(false);
      setIsOk(true);
    }
    END_LOADING();
  };

  const onCancel = () => {
    setOpen(false);
  };

  const afterClose = () => {
    if (isOk) {
      handleOk();
    } else {
      handleCancel();
    }
  }

  return (
    <CommonModal
      title="设置分拣道口"
      open={open}
      onOk={onOk}
      onCancel={onCancel}
      width={500}
      afterClose={afterClose}
    >
      <Form
        form={form}
        name="config-sort-cross"
        initialValues={{
          outNum: record.outNum,
        }}
      >
        <Form.Item
          label="分拣道口"
          name="outNum"
          rules={[
            { required: true, message: '请输入分拣道口' },
            {
              pattern: /^[1-9]\d*$/g,
              message: '请输入正整数',
            },
          ]}
        >
          <InputNumber
            style={{ width: '300px' }}
            min={1}
            max={9999}
            placeholder="请输入分拣道口"
          />
        </Form.Item>
      </Form>
    </CommonModal>
  );
};

export default AddSortCross;
